<template>
  <div>
    <a-row :gutter="24" style="margin-bottom: 12px;">
      <a-col :md="24">
        <a-input :placeholder="searchPlaceholder" :allowClear="true" v-model="text" @keyup.enter="searchText" @change="onChange" ref="inputText" style="width:300px;margin-right:8px;" />
        <a-button type="primary" @click="searchText">查询</a-button>
      </a-col>
    </a-row>
    <div class="tags-toggle">
      <div class="left">
        <p style="font-weight: 500;">查询标签</p>
        <div class="tags">
          <template v-for="(tag, index) in rootArray">
            <template v-if="tag.codes.length > 0">
              <a-tooltip v-if="tooltipString(tag.names).length > 20" :key="tag.title" :title="tooltipString(tag.names)">
                <a-tag :key="tag.title" :closable="true" @close="() => handleClose(tag, index)"> {{ tag.title }}: {{ tag.names | longString }} </a-tag>
              </a-tooltip>
              <a-tag v-else :key="tag.title" :closable="true" @close="() => handleClose(tag, index)"> {{ tag.title }}: {{ tag.names | arrToString }} </a-tag>
            </template>
          </template>
        </div>
      </div>
      <a-button type="link" @click="toggleAdvanced"> {{ advanced ? '收起筛选' : '展开筛选' }}<a-icon :type="advanced ? 'up' : 'down'" /> </a-button>
    </div>
    <collapse>
      <div class="tags-content" ref="tagsContent" v-show="advanced">
        <QueryTreePare :treeData="departTree" :layer="0" @update="update"></QueryTreePare>
      </div>
    </collapse>
  </div>
</template>
<script>
import QueryTreePare from './QueryTreePare'
import collapse from '../_util/collapse'
export default {
  props: {
    // 筛选树
    treeData: {
      type: Array
    },
    // 搜索框Placeholder
    searchPlaceholder: {
      type: String,
      required: false,
      default: '请输入'
    },
    // 搜索时保留的筛选项
    searchKeep: {
      type: Array,
      required: false,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      rootArray: [],
      departTree: [],
      advanced: false,
      text: ''
    }
  },
  components: { collapse, QueryTreePare },
  computed: {
    tooltipString() {
      return v => {
        return v.join('、')
      }
    }
  },
  filters: {
    arrToString(v) {
      return v.join('、')
    },
    longString(v) {
      return v.join('、').slice(0, 20) + '...'
    }
  },
  watch: {
    treeData: {
      handler(val) {
        let list = JSON.parse(JSON.stringify(val))
        let data = this.handleArr(list)
        this.departTree = data.map(item => {
          const checked = {
            checked: [],
            checkedName: []
          }
          return { ...item, ...checked }
        })
        this.initialRootArray(val)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 删除筛选条件中的标签
    handleClose(removedTag, index) {
      // console.log('removedTag',removedTag, index)
      const result = this.departTree.filter(item => item.code == removedTag.code)
      if (result.length > 0) {
        this.setTagList(result)
      }
      const resultList = this.rootArray.filter(e => e.code == removedTag.code)
      if (resultList.length > 0) {
        resultList[0].codes = []
        resultList[0].names = []
        resultList[0].list = []
      }
      this.$emit('updateParams', this.rootArray)
      // console.log('handleClose rootArray', this.rootArray)
      // console.log('handleClose departTree', this.departTree)
    },
    // 处理筛选条件中删除的标签数组
    setTagList(data) {
      for (let item of data) {
        if (item.children && item.children.length > 0) {
          const result = item.children.filter(e => e.leaf == true)
          if (item.children.length == result.length) {
            Object.assign(item, {
              checkValue: [],
              indeterminate: false,
              checkAll: false,
              checkList: []
            })
          } else {
            this.setTagList(item.children)
          }
        }
      }
    },
    // 展开收起
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    // 更新回传打标的值
    update(value) {
      console.log(value)
      // 处理rootArray
      const result = this.rootArray.filter(v => value.code.includes(v.code))
      if (result.length > 0) {
        // 处理list
        if (result[0].list.length == 0) {
          // list 完全为空
          result[0].list = [...result[0].list, ...value.codes]
        } else {
          // list非空
          // 含有对应code的list
          let listResult = result[0].list.filter(e => e.code.includes(value.code))
          // 非含有对应code的list
          let notListResult = result[0].list.filter(e => !e.code.includes(value.code))
          if (value.codes.length == 0) {
            listResult = []
          } else {
            listResult = value.codes
          }
          // console.log(listResult)
          result[0].list = [...notListResult, ...listResult]
        }
        // 处理codes & names
        if (result[0].list.length > 0) {
          result[0].codes = result[0].list.map(e => e.code)
          result[0].names = result[0].list.map(e => e.title)
        } else {
          result[0].codes = []
          result[0].names = []
        }
        console.log(result)
      }
      console.log(this.rootArray)
      // 更新departTree
      const resultTree = this.departTree.filter(v => value.code.includes(v.code))
      if (resultTree.length > 0) {
        this.updateTree(resultTree, value)
      }
      console.log('departTree', this.departTree)
      this.$emit('updateParams', this.rootArray)
    },
    updateTree(list, obj) {
      for (let item of list) {
        if (item.children && item.children.length > 0) {
          const result = item.children.filter(e => e.leaf)
          if (result.length == item.children.length) {
            if (item.code == obj.code) {
              if (obj.codes.length > 0) {
                Object.assign(item, {
                  checkValue: obj.codes,
                  indeterminate: !!obj.codes.length && obj.codes.length < item.children.length,
                  checkAll: obj.codes.length == item.children.length ? true : false,
                  checkList: obj.codes.map(e => e.code)
                })
              } else {
                Object.assign(item, {
                  checkValue: [],
                  indeterminate: false,
                  checkAll: false,
                  checkList: []
                })
              }
            }
          } else {
            this.updateTree(item.children, obj)
          }
        }
      }
    },
    // 处理departTree
    handleArr(data) {
      for (let item of data) {
        if (item.children && item.children.length > 0) {
          const result = item.children.filter(v => v.leaf == true)
          if (result.length == item.children.length) {
            // ------2021-12-9 取消初始化查询所有标签-------
            /* Object.assign(item, {
              checkValue: item.children,
              indeterminate: false,
              checkAll: true,
              checkList: item.children.map(e => e.code)
            }) */
            Object.assign(item, {
              checkValue: [],
              indeterminate: true,
              checkAll: false,
              checkList: []
            })
          } else {
            this.handleArr(item.children)
          }
        } else {
          Object.assign(item, {
            checkValue: [],
            indeterminate: false,
            checkAll: false,
            checkList: []
          })
        }
      }
      return data
    },
    // 初始化RootArray
    initialRootArray(data) {
      // console.log('------初始化RootArray-----初始化RootArray')
      this.rootArray = data.map(e => {
        return {
          code: e.code,
          title: e.title,
          codes: [],
          names: [],
          list: []
        }
      })
      // ------2021-12-9 取消初始化查询所有标签-------
      /* for (let item of this.rootArray) {
        let code = item.code
        let result = this.departTree.filter(e => e.code == code)
        if (result.length > 0) {
          let arr = []
          item.list = this.getInitialRootArrayList(result, arr)
          item.codes = item.list.map(e => e.code)
          item.names = item.list.map(e => e.title)
        }
      } */
      // console.log(this.rootArray)
    },
    getInitialRootArrayList(list, arr) {
      for (let item of list) {
        if (item.children && item.children.length > 0) {
          const result = item.children.filter(e => e.leaf)
          if (item.children.length == result.length) {
            arr.push.apply(arr, item.children)
          } else {
            this.getInitialRootArrayList(item.children, arr)
          }
        }
      }
      return arr
    },
    onChange(e) {
      // 监听allowClear
      if (e.type == 'click') {
        this.searchText()
      }
    },
    searchText() {
      this.activeCode = ''
      this.$emit('updateSearchText', this.text)
      // 按需保留筛选条件
      if (this.searchKeep.length > 0) {
        if (this.text.length > 0) {
          let list = this.rootArray.map(item => {
            if (!(this.searchKeep.indexOf(item.title) > -1)) {
              item = {
                checkValue: [],
                codes: [],
                names: [],
                title: item.title
              }
            }
            return item
          })
          this.rootArray = JSON.parse(JSON.stringify(list))

          // 按需清除筛选项
          for (let item of this.departTree) {
            if (!(this.searchKeep.indexOf(item.name) > -1)) {
              let arr = item.children.filter(e => e.children != undefined)
              if (arr.length > 0) {
                for (let child of item.children) {
                  if (!(this.searchKeep.indexOf(child.name) > -1)) {
                    child.checkList = []
                    child.checkValue = []
                    child.checkAll = false
                    child.indeterminate = false
                  }
                }
              } else {
                item.checkList = []
                item.checkValue = []
              }
            }
          }
          this.$emit('updateParams', this.rootArray)
        } else if (this.text.length == 0) {
          this.$emit('updateParams', this.rootArray)
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.tags-toggle {
  display: flex;
  justify-content: space-between;
  // align-items: center;
  margin: 0;
  // min-height: 36px;
  .left {
    display: flex;
    // align-items: center;
    margin: 0;
    font-size: 14px;
    line-height: 36px;
    margin-bottom: 8px;
    > p {
      width: 60px;
      margin: 0 12px 0 0;
      white-space: nowrap;
    }
    /deep/ .ant-tag {
      font-size: 14px;
      margin: 8px 24px 8px 0;
      line-height: 24px;
    }
  }
  button {
    margin-top: 2px;
  }
}
</style>

